var toolflagtip=decodeURI(window.location.href).split("?")[1].split("&")[0].replace("cls=","")
var original=""
var show=""
var ajaxPath="center.php"
//通过计数图片实现修改时第一次进入这个页面就不用保存
var CImg=0
var tempCimg=0
//调试开关
debug="no"
// 在搜索框中输入内容，按下回车键就进行搜索
window.onload=function()
{   
    readArea=document.getElementById("readArea")
    original=readArea.innerHTML
    //工具栏填充数据
    headShow()

    //获得所有的类
    getAllCls()

    //判断登录
    pandLogin()

    keyDonwSearch()
    //图片加载提示
    imgLoadInit()
    //删除提示框居中
    confirmToCenter()

}
//跳转到导入界面
function   toEnter()
{
 window.location.href="edite.php?subEd=no"
}

//这里是跳转到编辑页面
function toEdite()
{
 ch=document.getElementById("nChange")
 if(ch.value=="yes")
 {
  alert("不能修改，请点击链接")
  return 
 }
 cls=document.getElementById("ofcls").getElementsByTagName("span")[2].innerText.replace(/\s*/ig,"").replace(":","")
 title=document.getElementById("title").getElementsByTagName("span")[1].innerText.replace(/\s*/ig,"")
 contents=encodeURI(document.getElementById("contents").innerHTML)
 subEd="yes"
 window.location.href="edite.php?cls="+cls+"&title="+title+"&subEd="+subEd
}

//点击导航后显示菜单
function toReadShow(cls,e)
{
 toolflagtip=cls
 document.getElementById("nChange").value="yes"
 more=document.getElementById("more")
 var clsBox=document.getElementById("cls")
 more.innerText="more"
 readArea=document.getElementById("readArea")
 dic={"flag":"getCls","cls":cls}
 ajax(dic,ajaxPath,"POST",js=true,function(e)
 {
    window.scrollTo(0,0)
    data=JSON.parse(e)
    insert=""
    var dic={}

    for(i in data)
    {
        if(!Object.keys(dic).includes(data[i]["cls"]))
        {
            dic[data[i]["cls"]]=[data[i]]
        }
        else
        {
            dic[data[i]["cls"]].push(data[i])
        }
    }
    var it=0
    for( k in dic)
    {
        insert+="<div class='showArea' >\
        <p class='showCls'>\
        <span onclick=toIndexShow('"+k+"',this)>"+k+"</span>\
        <span id='back'  onclick=back() class='fa fa-mail-reply' aria-hidden='true'></span></p>"
        for( v in dic[k])
        {
            insert+="<p class='showTitle'>"+(it+1)+"、"+"\
            <a  onclick=toRead('"+k+"','"+dic[k][v]["title"]+"')>"+dic[k][v]["title"]+"</a></p>"
            it+=1
        }
    }
    insert+="</div>"
    document.getElementById("readArea").innerHTML=insert
    clsBox.style.display="none"
    imgLoadInit()

 })

}


//点击在阅读页面显示的标题后在阅读页面进行显示
function toRead(cls,title)
  {

    if(pandLogin()=="yes")
    {
      window.location.href="read.php?cls="+cls+"&title="+title+"&nChange=no"

    }
    else
    {
      window.location.href="/"
    }

}

// 点击more显示所有的分类
function showCls(e) 
{
 closeOrOpen=e.innerText.replace(/\s*/ig,"")
 if(closeOrOpen=="more")
 {
  document.getElementById("cls").style.display="block"
  e.innerText="close"
 }
 else
 {
  document.getElementById("cls").style.display="none"
  e.innerText="more"
 }
}



//这里是模糊搜索，并按照类别显示
function searchKey()
{
    searchId=document.getElementById("searchValue")
    searchValue=searchId.value.replace(/\s*/ig,"")
    if (searchValue.length==0) 
    {
        window.location.reload(true)
        return
    }
    var dic={"flag":"findFile","searchValue":searchValue}
    ajax(dic,ajaxPath,"POST",js=true,function(e)
    {
        data=JSON.parse(e)
        insert=""
        dic={}
        for(index in data)
        {
            if( !Object.keys(dic).includes(data[index]["cls"]))
            {
                dic[data[index]["cls"]]=[data[index]["title"]]
            }
            else
            {
                dic[data[index]["cls"]].push(data[index]["title"])
            }
        }

        for( k in dic)
        {
            insert+="<div class='showArea' ><p class='showCls'>\
            <span onclick=toIndexShow('"+k+"',this)>"+k+"</span>\
            <span id='back'  onclick=back() class='fa fa-mail-reply' aria-hidden='true'>\
            </span></p>"
            for( v in dic[k])
            {
                insert+="<p class='showTitle'>"+(v*1+1)+"、\
                <a  class='showTitle' onclick=toRead('"+k+"','"+dic[k][v]+"')>"+dic[k][v]+"</a></p>"
            }
            insert+="</div>"
        }
        document.getElementById("readArea").innerHTML=insert
        
    })
}



//打印业务
function  printer()
{
 if(isMobile())
 {
  alert("手机浏览不能打印")
 }
 else
 {
   var cont=document.getElementById("contents")
   if(cont!=null)
   {
    cont=cont.innerHTML
    var p=window.open("printer","","")
     p.document.write(cont)
     p.document.location.reload()
     p.print()
     p.close()
   }
   else
   {
    alert("请打开具体的链接进行打印")
   }
   
 }
}


//删除文本和图片
function toDele(tips)
{ 
  ch=document.getElementById("nChange")
  var confirmBox=document.getElementById("confirmBox")
  var tipsTitle=document.getElementById("tipsTitle")
  var ofcls=document.getElementById("ofcls").innerText
  var title=document.getElementById("title").innerText
  if(ch.value=="yes")
  {
    alert("不能删除")
    return 
  }

  if(tips=="yes")
  {
    var cls=document.getElementById("toCls").innerText.replace(/\s*/ig,"").replace(":","")
      var title=document.getElementById("title").getElementsByTagName("span")[1].innerText.replace(/\s*/ig,"")
      var data={"flag":"dele","cls":cls,"title":title}
      ajax(data,"center.php","POST",js=true,function(e)
      {
         confirmBox.style.display="none"
         window.location.href="log.php"
      })
  }
  else if(tips=="no")
  {
    confirmBox.style.display="none"
  }
  else
  {

    tipsTitle.innerText="是否删除:"+ofcls+" "+title+"文件"
    confirmBox.style.display="block"
    confirmToCenter()
  }
}

//点击具体分类之后返回
function back()
{
 readArea.innerHTML=original
        ch=document.getElementById("nChange")
 ch.value="no"
}

//判断是否是手机
 function isMobile() 
{
 const regExp = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i;
 return regExp.test(navigator.userAgent);
}

function toCls()
{
 var toCls=document.getElementById("toCls").innerText.replace(/\s+/ig,"").replace(":","")
 toReadShow(toCls,'toCls')
}



//登录
function pandLogin()
{

   var usr=getCookie("usr")
   var passWord=getCookie("passWord")

   if(usr!="th"||passWord!="w2009")
   {
        return "no"
   }
   else
   {
    getBigImg()
    return "yes"
   }
}


// 获取cookie
function getCookie(keyIndex)
{
    if(document.cookie.length==0)
    {
        return "no"
    }
    else
    {
        var cookies=document.cookie.split(";")
    }
    
    for(var i=0;i<cookies.length;i++)
    {
        var sp=cookies[i].split("=")
        var key=sp[0].trim()
        var value=sp[1].trim()
        if(keyIndex==key)
        {
            return value
        }
    }
    return "no"
}


// 获取cookie
function getCookie(keyIndex)
{
    var cookies=document.cookie.split(";")
    for(var i=0;i<cookies.length;i++)
    {
        var sp=cookies[i].split("=")
        var key=sp[0].trim()
        var value=sp[1].trim()
        if(keyIndex==key)
        {
            return value
        }
    }
    return "no"
}


//点击图片进行放大
function getBigImg()
{   
    var contents=document.getElementById("contents")
    var imgList=[]
    if(contents!=null)
    {
        imgList=contents.getElementsByTagName("img")
    }
    
    var bigImgSrc=document.getElementById("bigImgSrc")
    var bigImg=document.getElementById("bigImg")
    var bigImgBox=document.getElementById("bigImgBox")
    var bottonBox=document.getElementById("bottonBox")
    var bigImgValue=document.getElementById("bigImgValue")
    var big=document.getElementById("big")
    var small=document.getElementById("small")
    var rn=document.getElementById("rn")
    var body=document.getElementsByTagName("body")[0]

    for(var i=0;i<imgList.length;i++)
    {
        imgList[i].onclick=function()
        {
           bigImgSrc.src=this.src
           bigImg.style.display="block"
           var w=this.offsetWidth
           var h=this.offsetHeight
           var ttop=(body.offsetHeight-h-bottonBox.offsetHeight)/2
           bigImgSrc.style.width=w+"px"
           bigImgSrc.style.height=h+"px"
           bigImg.style.height=body.offsetHeight+"px"

           //让图片在画布上下居中
           bigImgBox.style.marginTop=ttop+"px"
           

           //点击图片后滚动到对应位置
           window.scrollTo(0,ttop+bigImgSrc.offsetHeight+bottonBox.offsetHeight-window.innerHeight+20)

           
           //按比例放大
           big.onclick=function()
           {    
                var rw=parseInt(bigImgSrc.style.width.replace("px",""))
                var rh=parseInt(bigImgSrc.style.height.replace("px",""))
                bigImgSrc.style.width=rw*(100+parseInt(bigImgValue.value))/100+"px"
               
                bigImgSrc.style.height=rh*(100+parseInt(bigImgValue.value))/100+"px"
                bigImgBox.style.marginTop=(body.offsetHeight-bigImgBox.offsetHeight-bottonBox.offsetHeight)/2+"px"
                document.scrollTop=(body.offsetHeight-bigImgBox.offsetHeight-bottonBox.offsetHeight)/2
                if(bigImgSrc.offsetHeight+100>body.offsetHeight)
                {
                     bigImg.style.height=bigImg.offsetHeight+parseInt(bigImgValue.value)+"px"
                }
           }

           //按比例缩小
           small.onclick=function()
           {    
                var rw=parseInt(bigImgSrc.style.width.replace("px",""))*(100-parseInt(bigImgValue.value))/100
                var rh=parseInt(bigImgSrc.style.height.replace("px",""))*(100-parseInt(bigImgValue.value))/100
                if(rw>200&&rh>200)
                {
                    bigImgSrc.style.width=rw+"px"
                    bigImgSrc.style.height=rh+"px"
                }
                else if(rw<200)
                {   
                    alert("宽度最少200")
                    return
                }
                else
                {
                     alert("高度最少200")
                    return
                }

                bigImgBox.style.marginTop=(body.offsetHeight-bigImgBox.offsetHeight-bottonBox.offsetHeight)/2+"px"
                 
                //如果画布大于页面可以进行缩小
                var bigimgNH=bigImg.offsetHeight*(100-parseInt(bigImgValue.value))/100
                if(bigimgNH>body.offsetHeight)
                {
                     bigImg.style.height=bigimgNH+"px"
                }
           }

           rn.onclick=function()
           {
                bigImg.style.display="none"
                bigImgSrc.style.width=w+"px"
                bigImgSrc.style.height=h+"px"
                bigImg.style.height=body.offsetHeight+"px"
           }
        }
    }
}



// ajax函数
function ajax(dic,url,method,js=true,fun="")
{
    var xhr=new XMLHttpRequest()
    xhr.open(method,url,true)

    xhr.onreadystatechange = function(e)
    
    {
        
        if(xhr.readyState == 4&&xhr.status==200)
        {  
            if(debug=="yes")
            {
                console.log(xhr.response)
            }
            
            if(fun!="")
            {
                fun(xhr.response)
            }
        }
    }

    if(js)
    {
        xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
        xhr.send(JSON.stringify(dic))
    }
    else
    {
        uploadPercent=0
        xhr.upload.addEventListener("progress",function(e)
        {
            uploadPercent=(e.loaded/e.total)*100
            showStatus("已经上传:"+uploadPercent+"%")
        })
        xhr.send(dic)
    }
}



//点击类别按钮在主页显示相应的标题
function toIndexShow(cls,e)
{
    more=document.getElementById("more")
    more.innerText="more"
    readArea=document.getElementById("readArea")
    getToEnter=document.getElementById("toEnter")
    var data={"flag":"getCls","cls":cls}
    ajax(data,ajaxPath,"POST",js=true,function(e)
    {
        window.scrollTo(0,0)
        data=JSON.parse(e)
        insert=""
        var dic={}
        for(i in data)
        {
            if(!Object.keys(dic).includes(data[i]["cls"]))
            {
                dic[data[i]["cls"]]=[data[i]]
            }
            else
            {
                dic[data[i]["cls"]].push(data[i])
            }
        }
        it=1

    
        for( k in dic[cls])
        {
            
            insert+="<p class='showTitle'>"+it+"、<a href='#' class='showTitle' \
            onclick=toRead('"+dic[cls][k]["cls"]+"','"+ dic[cls][k]["title"]+"')\
            >"+dic[cls][k]["title"]+"</a></p>"
            it+=1
         }
         readArea.innerHTML="<div class='showArea'><p class='showCls'>\
         <span>"+cls+"</span>\
         <span id='back'onclick=back() class='fa fa-mail-reply' aria-hidden='true'>\
         </span></p>"+insert+"</div>"

         getToEnter.setAttribute("href",getToEnter.getAttribute("href").split("?")[0]+"?cls="+cls+"&&subEd=no");
     })
}

// 获取所有分类
function getAllCls()
{   
    var data={"flag":"getAllCls"}
    var clsList=[]

    ajax(data,ajaxPath,"POST",js=true,function(e)
    {

        var data=JSON.parse(e)
        var clsBox=document.getElementById("cls")
        var row=0
        var insert=""
        for(k in data)
        {
            row=data[k]
            cls=row["cls"]
            if(clsList.includes(cls))
            {
                continue
            }
            else
            {
                clsList.push(cls)
                insert+="<span class='moreCls' onclick=toReadShow('"+cls+"',this)>"+cls+"</span>";
            }
        }
        clsBox.innerHTML=insert
        
    })
}


//在搜索框中按下特定键盘进行搜索
function keyDonwSearch()
{   
    var searchValue=document.getElementById('searchValue')
    
    searchValue.onkeydown=function(e)
    {
        console.log(e)
        if("Enter"==e.code||e.code=="Space")
        {
            setTimeout("searchKey()",100)
        }
   }
}

function imgLoadInit()
{

    var contents=document.getElementById("contents")

    if(contents==null)
    {
        return
    }
    var img=contents.getElementsByTagName("img")
    CImg=img.length
    //每次进入要初始化
    tempCimg=0
    if(CImg>0)
    {
        showStatus("加载中.....",2000,"yes")
        for(var i=0;i<img.length;i++)
         {
            img[i].onload=imgLoad()
         }
    }
}
//图片加载进度
function imgLoad()
{
   tempCimg+=1
   if(CImg==tempCimg)
   {
        setTimeout(function()
        {
            showStatus("加载完成",1000,"no")
        },1000)
    }
}

//显示状态
function showStatus(info="测试",time=2000,showing="no")
{
    var status=document.getElementById("status")
    status.style.display="block"
    status.innerText="状态:"+info
    statusToCenter()
    if(showing=="no")
    {
    setTimeout(function()
    {
       status.style.display="none"
    },time)
    }
}

//让状态居中
function statusToCenter()
{
  var ele=document.getElementById("status")
  var viw=Math.ceil(document.getElementsByTagName("body")[0].offsetWidth)
  var x=(viw-ele.offsetWidth)/2
  ele.style.left=x+"px"
}

//删除提示框居中
function confirmToCenter()
{
    var w=document.getElementsByTagName("body")[0].offsetWidth
    var confirmBox=document.getElementById("confirmBox")
    confirmBox.style.left=(w-confirmBox.offsetWidth)/2+"px"
}
//修改浏览器尺寸时修改居中
window.addEventListener("resize",function()
{
  confirmToCenter()
  statusToCenter()
})
//空函数解决报错问题
function FileMouseD()
{

}
//空函数解决报错问题
function  FileMouseU()
{

}



